import TextEncoderLite from "../polyfill/TextEncoder";

function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return wx.arrayBufferToBase64 ? wx.arrayBufferToBase64(buffer) : btoa(binary);
}

// 使用示例
function encodeSvgToBase64(svgString) {
  // 首先将字符串转为ArrayBuffer
  const encoder = new TextEncoderLite();
  const data = encoder.encode(svgString);

  // 然后将ArrayBuffer转换为Base64
  const base64String = arrayBufferToBase64(data);
  
  // 返回带有data URL前缀的Base64字符串
  return 'data:image/svg+xml;base64,' + base64String;
}


function changeSvgColor(str, newColor) {
  // 解码Base64字符串为原始的SVG XML文本
  // const svgText = decodeURIComponent(atob(base64Str.split(",")[1])).replace(
  const svgString = decodeURIComponent(str).replace(
    /fill="[^"]*"/g,
    `fill="${newColor}"`
  );
  // 再次编码为Base64
  const updatedBase64 = encodeSvgToBase64(svgString)
  return updatedBase64;
}

export {
  changeSvgColor,
  
};
